
import configparser
from pathlib import Path

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

from logger_setup import log

SCRIPT_DIR = Path(__file__).resolve().parent
CONFIG_PATH = SCRIPT_DIR / 'config.ini'

class NoteGenerator:
    """Uses an OpenAI-compatible API to generate notes from a transcript."""
    def __init__(self):
        self.config = configparser.ConfigParser()
        self.config.read(CONFIG_PATH)
        self.llm = self._load_llm_from_profile()
        self.chain = self._create_chain()
        log.info("NoteGenerator initialized.")

    def _load_llm_from_profile(self):
        active_profile = self.config.get('LLM', 'active_profile')
        log.info(f"Loading LLM using active profile: '{active_profile}'")
        profile = self.config[active_profile]
        return ChatOpenAI(
            model=profile.get('model_name'),
            api_key=profile.get('api_key'),
            base_url=profile.get('base_url'),
            temperature=0.7
        )

    def _create_chain(self):
        prompt_template = """
        你是一位顶级的学习助理和课程内容分析师。
        你的任务是阅读以下课程文字稿，并将其整理成一份结构清晰、重点突出、易于复习的 Markdown 格式学习笔记。

        请严格按照以下 Markdown 格式输出，不要有任何多余的解释或开场白：

        # 课程核心摘要
        [这里是对整个课程内容的高度概括，说明白了这节课主要讲了什么]

        ## 关键知识点
        - [知识点一]
        - [知识点二]
        - [知识点三]

        ## 详细笔记
        ### 1. [第一个知识点的标题]
        [这里对第一个知识点进行详细的解释、举例或阐述]

        ### 2. [第二个知识点的标题]
        [这里对第二个知识点进行详细的解释、举例或阐述]

        ## 思考与拓展
        - [提出一个或多个基于本课程内容，可以进一步思考或探索的问题]

        --- 这是课程的文字稿内容 ---
        {transcript_text}
        --- 文字稿内容结束 ---

        请开始生成笔记：
        """
        prompt = ChatPromptTemplate.from_template(prompt_template)
        parser = StrOutputParser()
        return prompt | self.llm | parser

    def generate_notes_for_file(self, transcript_path: Path):
        """
        Generates and saves notes for a single transcript file.
        """
        log.info(f"--- Starting Note Generation for: {transcript_path.name} ---")
        try:
            with open(transcript_path, 'r', encoding='utf-8') as f:
                content = f.read()
            if not content.strip():
                log.warning(f"Transcript file {transcript_path} is empty. Skipping.")
                return

            log.info("Invoking LLM to generate notes... (This may take some time)")
            notes = self.chain.invoke({"transcript_text": content})
            
            output_path = transcript_path.parent / "notes.md"
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(notes)
            
            log.info(f"Successfully saved notes to: {output_path}")

        except Exception as e:
            log.error(f"Failed to generate notes for {transcript_path}. Error: {e}", exc_info=True)
        log.info("--- Note Generation Complete ---")
